package xiangyi.controller;

import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelWriter;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import xiangyi.service.IExcelReaderService;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Project Name: Tmall_demo-master
 * Package Name: com.xq.tmall.controller.xiangyi
 * File Name: ExcelReaderController
 * 2022/9/9 20:04 - 李宗宝
 */
@Controller
public class ExcelReaderController {

    protected Logger logger = LogManager.getLogger(ExcelReaderController.class);

    @Autowired
    private IExcelReaderService iExcelReaderService;

    /**
     * 上传打卡记录，计算工时、加班时长等并导出
     * 打卡记录处理
     * Author LiZongBao
     * Date 2022/9/10 22:06
     * @param file
     * @param response
     * @return void
     **/
    @RequestMapping(value = "xiangyi/uploadExcel", method = RequestMethod.POST)
    public void uploadExcel(@RequestParam("file") MultipartFile file, HttpServletResponse response){
        ExcelWriter writer = iExcelReaderService.uploadExcel(file);
        response.reset();
        response.setContentType("multipart/form-data");
        response.setCharacterEncoding("utf-8");
        //product.xls是弹出下载对话框的文件名，不能为中文，中文请自行编码
        response.setHeader("Content-disposition", "attachment; filename = EmployeeSalaryDetails.xls");
        ServletOutputStream out = null;
        try {
            out = response.getOutputStream();
            writer.flush(out, true);
        } catch (IOException e) {
            logger.error("导出审计日志获取输出流失败:{}", e.getMessage());
        } finally {
            try {
                // 关闭writer，释放内存
                writer.close();
                out.flush();
                //此处记得关闭输出Servlet流
                IoUtil.close(out);
            } catch (IOException e) {
                logger.error("导出审计日志关闭输出流失败:{}", e.getMessage());
            }
        }
    }

}
